// base64 -> file
export const base64ToFile = (dataUrl: string, filename = '图片.png') => {
  const arr = dataUrl.split(',')
  const mime = arr[0].match(/:(.*?);/)?.[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}

// file -> base64
export const FileToBase64 = (file: File) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    let fileResult: string = ''
    reader.readAsDataURL(file)
    reader.onload = () => {
      fileResult = reader.result as string
    }
    reader.onerror = (error) => reject(error)
    reader.onloadend = () => resolve(fileResult)
  })
}

// 下载base64
export const exportFile = (base64_str: string, fileName: string) => {
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = base64_str
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(base64_str)
}

// url(http) -> base64
export const urlToBase64 = (imgSrc: string) => {
  return new Promise((ok, no) => {
    const image = new Image()
    image.setAttribute('crossOrigin', 'anonymous')
    image.onload = function () {
      const canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      const context = canvas.getContext('2d') as CanvasRenderingContext2D
      context.drawImage(image, 0, 0, image.width, image.height)
      const base64_str = canvas.toDataURL('image/png')
      ok(base64_str)
    }
    image.src = imgSrc
  })
}

// file -> blob
export function fileToUrl(file: File) {
  const { type } = file
  return window.URL.createObjectURL(new Blob([file], { type }))
}
